package com.songcan.oauth.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songcan.model.basics.Area;
import com.songcan.model.oauth.SysDept;
import com.songcan.oauth.mapper.SysDeptMapper;
import com.songcan.oauth.service.SysDeptService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-04-29
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {


    @Override
    public void addDept(String name, Integer sort, Long parentId, String remark) {
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        String levelCode = "";
        SysDept sysDept = null;
        if(Objects.nonNull(parentId)){
            int childCount = count(Wrappers.lambdaQuery(new SysDept())
                    .eq(SysDept::getParentId,parentId).eq(SysDept::getDelFlag,0));
            SysDept  area = getById(parentId);
            if(childCount > 0){
                levelCode = area.getLevelCode() +"-"+ decimalFormat.format(childCount);

            }else{
                levelCode = area.getLevelCode()+"-"+"0001";
            }
        }else{
            sysDept = getOne(Wrappers.lambdaQuery(new SysDept()).isNull(SysDept::getParentId).orderByDesc(SysDept::getCreateTime).last(" limit 1"));
            if(Objects.isNull(sysDept)){
                levelCode = "0000";
            }else {
                levelCode = sysDept.getLevelCode();
            }
        }
        String[] level = levelCode.split("-");
        while (count(Wrappers.lambdaQuery(new SysDept()).eq(SysDept::getLevelCode,levelCode))>0){

            Long code = Long.valueOf(level[level.length-1]);
            code++;
            level[level.length-1] = String.valueOf(decimalFormat.format(code));
            levelCode = StringUtils.join(level,"-");
        }
        sysDept =new SysDept(IdWorker.getId(),name,null,levelCode,new Date(),null,0,parentId,remark);
        save(sysDept);
    }

}
